package RedisRpcUtils

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Uuid"
	"time"
)

func ExecuteChannel(request map[string]interface{}) (*commRedisRpc.ChannelRespondVO, error) {
	requestVO := &commRedisRpc.ChannelRequestVO{}
	err := Json.BuildObjectByMap(request, requestVO)
	if err != nil {
		return nil, err
	}

	// 旧版本的消息结构：channelType
	if requestVO.Type == "" {
		requestVO.Type = Map.GetOrDefault(request, "channelType", "").(string)
	}

	return executeChannel(requestVO)
}

func executeChannel(requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	channelType := requestVO.Type

	// 检查：参数是否为空
	if Method.HasEmpty(channelType) {
		return nil, errors.New("参数缺失：channelType")
	}

	// 检查：目标服务是否已经启动
	if !commRedisStatus.IsActive("channel", channelType, 60*1000) {
		return nil, errors.New("Channel服务尚未运行：" + channelType)
	}

	timeout := requestVO.Timeout
	if timeout == 0 {
		timeout = 2000
	}

	//填写UUID，从众多方便返回的数据中，识别出来对应的返回报文
	key := requestVO.Uuid
	if Method.HasEmpty(key) {
		key = Uuid.RandomUUID()
		requestVO.Uuid = key
	}

	// 发送数据
	commRedisRpc.Channel.Client.Request.Push(requestVO.Type, requestVO)

	// 等待消息的到达：根据动态key
	respond, err := commRedisRpc.Channel.Client.Respond.Pop(requestVO.Type, requestVO.Uuid, time.Duration(timeout+3000)*time.Millisecond)
	if err != nil {
		return nil, errors.New("设备响应超时：" + channelType)
	}

	return respond, nil
}

func ExecuteDevice(request map[string]interface{}) (*commRedisRpc.TaskRespondVO, error) {
	// 检查：目标服务是否已经启动
	if !commRedisStatus.IsActive("device", "device", 60*1000) {
		return nil, errors.New("device服务尚未运行")
	}

	requestVO := commRedisRpc.Type.TaskRequestVO.New()
	err := Json.BuildObjectByMap(request, requestVO)
	if err != nil {
		return nil, err
	}

	requestVO.ClientName = "manager"

	// 发送数据
	commRedisRpc.Device.Client.Request.Push(requestVO)

	// 等待消息的到达：根据动态key
	respond, err := commRedisRpc.Device.Client.Respond.Pop(requestVO.Uuid, time.Duration(requestVO.Timeout+3000)*time.Millisecond)
	if err != nil {
		return nil, errors.New("Device Service 响应超时")
	}

	return respond, nil

}
